#include "stdafx.h"
#include "Utils.h"

using namespace CryptoPP;
using namespace AppliedCryptography;

std::string Vector2HexStr(std::vector<byte>& v)
{
	byte* vBytes = new byte[v.size()];
	std::string vStr;

	for(unsigned int i=0; i<v.size(); ++i)
	{
		vBytes[i] = v[i];
	};

	//Base64Encoder hexEnc(new StringSink(certStr));
	HexEncoder enc(new StringSink(vStr));
	enc.Put(vBytes, v.size());
	enc.MessageEnd();

	delete vBytes;

	return vStr;
};

std::string Vector2B64Str(std::vector<byte>& v)
{
	byte* vBytes = new byte[v.size()];
	std::string vStr;

	for(unsigned int i=0; i<v.size(); ++i)
	{
		vBytes[i] = v[i];
	};

	//Base64Encoder hexEnc(new StringSink(certStr));
	Base64Encoder enc(new StringSink(vStr));
	enc.Put(vBytes, v.size());
	enc.MessageEnd();

	delete vBytes;

	return vStr;
};

void CopyKeyBytes(RSAFunction& key, ASN1Encoded& dest, bool fPublicKey)
{
	byte keyBytes[RSAKEYSIZE*3];
	std::string keyHexStr;
	HexEncoder hexEnc(new StringSink(keyHexStr));
	HexDecoder hexDec(new ArraySink(keyBytes, RSAKEYSIZE*3));

	//key.DEREncode(hexEnc);
	key.Save(hexEnc);
	hexEnc.MessageEnd();

	hexDec.Put((byte*) keyHexStr.c_str(), keyHexStr.size());
	hexDec.MessageEnd();

	dest.set(keyBytes, keyHexStr.size()/2);
};

void GetKeys(ASN1Encoded& asn1PrivateKey, ASN1Encoded& asn1PublicKey)
{
	AutoSeededRandomPool rng;

	// Generate Parameters
	InvertibleRSAFunction params;
	params.GenerateRandomWithKeySize( rng, RSAKEYSIZE );

	// Create Keys
	RSA::PrivateKey privateKey( params );
	RSA::PublicKey publicKey( params );

	CopyKeyBytes(publicKey, asn1PublicKey, true);
	CopyKeyBytes(privateKey, asn1PrivateKey, false);
};

